/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.warehouse.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.warehouse.entity.Device;
import com.thinkgem.jeesite.modules.warehouse.entity.Vendor;
import com.thinkgem.jeesite.modules.warehouse.service.DeviceService;
import com.thinkgem.jeesite.modules.warehouse.service.VendorService;

/**
 * deviceController
 * @author qrg
 * @version 2017-08-09
 */
@Controller
@RequestMapping(value = "${adminPath}/warehouse/device")
public class DeviceController extends BaseController {

	@Autowired
	private DeviceService deviceService;
	
	@Autowired
	private VendorService vendorService;
	
	@ModelAttribute
	public Device get(@RequestParam(required=false) String id) {
		Device entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = deviceService.get(id);
		}
		if (entity == null){
			entity = new Device();
		}
		return entity;
	}
	
	@RequiresPermissions("warehouse:device:view")
	@RequestMapping(value = {"list", ""})
	public String list(Device device, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Device> page = deviceService.findPage(new Page<Device>(request, response), device); 
		model.addAttribute("page", page);
		return "modules/warehouse/deviceList";
	}

	@RequiresPermissions("warehouse:device:view")
	@RequestMapping(value = "form")
	public String form(Device device, Model model) {
		List<Vendor> vendors = vendorService.findList(new Vendor());
		model.addAttribute("vendors",vendors);
		model.addAttribute("device", device);
		return "modules/warehouse/deviceForm";
	}

	@RequiresPermissions("warehouse:device:edit")
	@RequestMapping(value = "save")
	public String save(Device device, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, device)){
			return form(device, model);
		}
		deviceService.save(device);
		addMessage(redirectAttributes, "保存device成功");
		return "redirect:"+Global.getAdminPath()+"/warehouse/device/?repage";
	}
	
	@RequiresPermissions("warehouse:device:edit")
	@RequestMapping(value = "delete")
	public String delete(Device device, RedirectAttributes redirectAttributes) {
		deviceService.delete(device);
		addMessage(redirectAttributes, "删除device成功");
		return "redirect:"+Global.getAdminPath()+"/warehouse/device/?repage";
	}
	
	@RequiresPermissions("warehouse:device:edit")
	@RequestMapping(value = "checkDeviceSn")
	public String checkDeviceSn(String sn) {
		if (sn !=null && deviceService.getDeviceBySn(sn) == null) {
			return "true";
		}
		return "false";
	}
	
	
	@RequiresPermissions("warehouse:device:edit")
	@RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<Device> list = ei.getDataList(Device.class);
			
			for (Device device : list){
				try{	
					if ("true".equals(checkDeviceSn(device.getSn()))){
						BeanValidators.validateWithException(validator, device);
						deviceService.save(device);
						successNum++;
					}else{
						failureMsg.append("<br/>设备 "+ device.getName()+" 已存在; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>设备 "+device.getName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>设备 "+device.getName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条设备，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条设备"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入设备失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/warehouse/device/list?repage";
    }
	

	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("warehouse:device:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "设备数据导入模板.xlsx";
            String sn = "001";
    		List<Device> list = Lists.newArrayList(); list.add(deviceService.getDeviceBySn(sn));
    		new ExportExcel("设备数据", Device.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/warehouse/device/list?repage";
    }
	
	
	@RequiresPermissions("warehouse:device:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Device device, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "设备数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Device> page = deviceService.findPage(new Page<Device>(request,response,-1),device);
    		new ExportExcel("设备数据", Device.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出设备失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/warehouse/device?repage";
    }
	
	

}